package com.boarsoft.rpc.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.boarsoft.common.util.StringUtil;
import com.boarsoft.rpc.bean.RpcRegistry;
import com.boarsoft.rpc.core.RpcCore;

/**
 * Zone Info 工具类
 * 
 * @author Mac_J
 *
 */
public class ZoneClientUtil {
	/**
	 * 
	 * @return
	 */
	@Deprecated
	public static List<UidRange> getCurrZoneUidRange() {
		return refresh().get(System.getProperty("my.zone"));
	}

	/**
	 * 
	 * @param uid
	 * @return
	 */
	@Deprecated
	public static ZoneInfo route(String uid) {
		RpcRegistry mr = RpcCore.getCurrentInstance().getRpcContext().getMyRegistry();
//			String uid = String.format("%02d", uid);
		return new ZoneInfo(mr.getMetaString(uid, null));
	}

	/**
	 * 
	 * @return
	 */
	@Deprecated
	public static ZoneInfo queryZoneInfo() {
		return new ZoneInfo(System.getProperty("my.zone"));
	}

	/**
	 * 
	 * @return
	 */
	@Deprecated
	public static Map<String, List<UidRange>> refresh() {
		Map<String, List<UidRange>> map = new HashMap<>();
		RpcRegistry mr = RpcCore.getCurrentInstance().getRpcContext().getMyRegistry();
		String cz = null;
		int si = 0;
		for (int i = 0; i < 100; i++) {
			String uid = String.format("%02d", i);
			String z = mr.getMetaString(uid, null);
			if (StringUtil.isEmpty(z)) {
				throw new IllegalStateException("No uid zone info");
			}
			if (z.equals(cz)) {
				continue;
			}
			if (!map.containsKey(z)) {
				map.put(z, new ArrayList<UidRange>());
			}
			if (i > 0) {
				map.get(z).add(new UidRange(si, i));
			}
			si = i;
			cz = z;
		}
		return map;
	}

	@Deprecated
	public static List<ZoneInfo> queryAllZoneInfo() {
		List<ZoneInfo> lt = new ArrayList<ZoneInfo>();
		Map<String, List<UidRange>> map = refresh();
		for (String k : map.keySet()) {
			lt.add(new ZoneInfo(k));
		}
		return lt;
	}

	public static List<UidRange> getUidRange(String zoneName) {
		return refresh().get(zoneName);
	}
}